﻿using System.Diagnostics;
using Avalonia.Media.Imaging;
using KinonekoSoftware.ArkSpark.Core.Messages;
using KinonekoSoftware.ArkSpark.Documents.Primitives;
using KinonekoSoftware.ArkSpark.Runtimes.Presenters;
using KinonekoSoftware.Foundation.UI.Commands;

namespace KinonekoSoftware.ArkSpark.Runtimes.Presenters
{
    public sealed class PicturePresenter : DocumentElementPresenter<PictureElement>
    {
        public PicturePresenter(PictureElement element) : base(element)
        {
            RaiseUpdated(nameof(Description));
            RaiseUpdated(nameof(Source));
            SelectPictureCommand = new ActionCommand(DoSelectPictureCommand);
            ClearPictureCommand  = new ActionCommand(DoClearPictureCommand);
        }

        private async void DoSelectPictureCommand()
        {
            var args = new PictureElementUpdatedEventArgs(this);
            
            //
            //
            Debug.Assert(Bus is not null);
            
            //
            //
            Bus.OnNext(args);

            //
            //
            if (args.Task is not null && args.Task.Status == TaskStatus.Created)
            {
                //
                //
                args.Task.Start();
                
                //
                //
                await args.Task;
            }
            
            //
            // 报告已更改
            ElementUpdatedEventArgs.OnNext(Bus);
        }
        
        private void DoClearPictureCommand()
        {
            //
            //
            Source = null;
            
            //
            // 报告已更改
            ElementUpdatedEventArgs.OnNext(Bus);
        }

        public override bool UseWYSIWYGEditor => false;
        public override bool IsSelectable => false;

        public string Description
        {
            get => TargetElement.Description;
            set
            {
                TargetElement.Description = value;
                RaiseUpdated();
            }
        }

        public string Source
        {
            get => TargetElement.Source;
            set
            {
                TargetElement.Source = value;
                RaiseUpdated();
            }
        }

        public ICommandEX SelectPictureCommand { get; }
        public ICommandEX ClearPictureCommand  { get; }

    }
}